var categoryMap = {
	1:"创意设计",
	2:"基础部件",
	3:"整机套装",
	4:"应用配套"
};

var academyMap = {
	1:"中国科学院",
	2:"中国工程院",
	3:"国际欧亚科学院中国科学中心",
	4:"发展中国家科学院",
	99:"其它"
};

// 添加奖励
layui.use(['form', 'code', 'laydate','upload','layer','laytpl','element','laypage'], function() {
	var laydate = layui.laydate;
	form = layui.form;
	upload = layui.upload;
	layer = layui.layer;
	laytpl = layui.laytpl;
	element = layui.element;
	laypage = layui.laypage;



	layui.code();

	setAcademist();



    $(".addNewTask").on("click",function () {
        var params = {};
        params.projectId = $(".assignTaskProjectId").val();
        params.academistId = $(".academistId").val();

        if(!params.academistId){
            layer.msg("请选择院士专家");
            return false;
        }

        let academistList = $(".academistId").data("academistList");
        let academist;
        for(let i = 0; i < academistList.length;i++){
             let item = academistList[i];
             if(item.id == params.academistId){
                academist = item;
                break;
             }

        }

        AJAX.post(cgiMain.assignScoringTask,
            params,
            function (res) {

                if (res.code == '0000') {
                    $(".hadTaskAcademists").append("<div><lable>" + academist.name + "</lable>--<label>87分</label><a class='deleteAssignTask'>     删除</a></div>");
                    $(".hadTaskAcademists").on("click",'.deleteAssignTask',function (elem) {
                        // $(elem.target).parent().remove();
                        deleteAssignTask(elem);

                    });
                } else {
                    layer.msg(res.msg || "操作失败");
                }
            });
    });



	$(".closeAssignTask").on("click",function () {
        $(".assignTaskProjectId").val("");
        $(".hadTaskAcademists").html("");
        $("#taskModal").hide();
    });

	function lookApplyInfo(dom){
		var projectId = $(dom.target).attr("data-id");
		var projectList = $(".projectList").data("projectList");
		var applyProject =  null;
		$(".detailDiv").html(JSON.stringify(projectList));
		for(let i =0;i < projectList.length;i++){
			if(projectId == projectList[i].id){
				applyProject = projectList[i];
				break;
			}
		}
		$(".projectId").val(applyProject.id);
		//申请人信息
		$(".name").val(applyProject.applicantBase.name);
		$(".sex").val(applyProject.applicantBase.sex == 1?"男":"女");
		$(".photo").prop("src",applyProject.applicantBase.photo);
		$(".registeredAddress").val(applyProject.applicantBase.registeredProvince + applyProject.applicantBase.registeredCity + applyProject.applicantBase.registeredArea);
		$(".liveAddress").val(applyProject.applicantBase.liveProvince + applyProject.applicantBase.liveCity + applyProject.applicantBase.liveArea + " " + applyProject.applicantBase.address);
		//项目信息
		$(".projectName").val(applyProject.projectName);
		$(".projectContext").val(applyProject.projectContext);
		$(".serviceComment").val(applyProject.serviceComment);
		$(".marketUserComment").val(applyProject.marketUserComment);
		$(".businessPattern").val(applyProject.businessPattern);
		$(".runData").val(applyProject.runData);
		$(".coreResource").val(applyProject.coreResource);
		PDFObject.embed(applyProject.bpUrl,"#previewBp");

		if(applyProject.categorys){
			let projectCategory = applyProject.categorys[0];
			$(".categoryName").val(projectCategory.categoryName);
			$(".secondCategoryName").val(projectCategory.secondCategoryName);
			$(".thirdCategoryName").val(projectCategory.thirdCategoryName);
		}

		if(applyProject.applyList){
			let applyItem = applyProject.applyList[0];
			$(".acadPhoto").prop("src",applyItem.academist.photo);
			$(".acadName").val(applyItem.academist.name);
			$(".acadAcademyName").val(academyMap[applyItem.academist.academy]);
			$(".acadResearchDomain").val(applyItem.academist.researchDomain);
		}

		if(applyProject.appendixList){
			if($(".appendixUrl").length >=1){

			}else{
				for(let i = 0;i < applyProject.appendixList.length;i++){
					var appendix = applyProject.appendixList[i];
					$(".bpFileDiv").append("<div style='padding: 20px;display: inline;'><img class='appendixUrl' src='" + appendix.appendixUrl +"' width='100px' height='100px' /></div>");
				}
			}
		}


		$("#myModal").show();
	}




	function  setSelect(dom,data){
		for(let item in data){
			$(dom).append("<option value='" + item +"'>"+ data[item] +"</option>")
		}
		form.render("select");
	}



// 添加教育经验
	$(".add_btn").on("click", function() {
		$("#myModal").show();
		$("#myModal input, #myModal textarea").val("");

	});


//设置二级分类
	AJAX.query(cgiMain.getDict,
		{type:5},
		function (res) {
			if(res.code=='0000'){
				setSelect($("select[name='secondCategory']"), res.result);
				form.render('select');
				form.on("select(secondCategory)",function (data) {
					$("select[name='thirdCategory']").html("");
					setThirdCategorySelect(data.value);
				});
			}
		});

	function setFourthCategory(thirdCategory) {
		$(".fourthCategoryDiv").hide();
		$(".fourthCategoryItemDiv").html("");
		if(!thirdCategory)return;
		AJAX.query(cgiMain.getDict,
			{type:5,parentId:thirdCategory},
			function (res) {
				if(res.code == "0000"){
					$(".fourthCategoryDiv").show();
					for(let item in res.result){
						$(".fourthCategoryItemDiv").append("<input type='radio' name='fourthCategory'  value='" + item +"' title='"+ res.result[item] +"' lay-filter='fourthCategory'/>")
					}
					form.render();

				}
			});
	}
	function setThirdCategorySelect(secondCategory,defaultChoice){
		AJAX.query(cgiMain.getDict,
			{type:5,parentId:secondCategory},
			function (res) {
				if(res.code=='0000'){
					setSelect($("select[name='thirdCategory']"), res.result);
					form.render('select');
					if(defaultChoice){
						// $(".thirdCategory").val(33);
						form.render('select');
					}

					setFourthCategory($(".thirdCategory").val());
					form.on("select(thirdCategory)",function (data) {
						setFourthCategory($(".thirdCategory").val());
					});

				}
			});
	}

	//初始化列表
	setTimeout(search,500);

	function search(){
		$(".projectList").html("");
		var searchProjectName = $(".searchProjectName").val();
		AJAX.post(cgiMain.applicantAllProject,
			{pageNum:1,pageSize:10,searchProjectName:searchProjectName},
			function (res) {

				if(res.code == '0000'){
					$(".projectList").data("projectList",res.result.list);
					var tpl = $("#projectItemTpl").html();
					var resultPage = res.result;
					for(var i = 0; i < resultPage.list.length;i++){
						var item = resultPage.list[i];
						item.projectCategoryName = categoryMap[item.projectCategory];
						laytpl(tpl).render(item,function (html) {
							$(".projectList").append(html);

							$(".projectList").on("click",'.lookApplyInfo',function (elem) {
								lookApplyInfo(elem);
							});
							$(".projectList").on("click",'.assignTask',function (elem) {
                                assignTask(elem);
							});


						});
					}

					//执行一个laypage实例
					laypage.render({
						elem: 'projectPagination'
						,limit: 10
						,limits:[10]
						,theme:'#1E9FFF'
						,layout:['prev', 'page', 'next','limit','count']
						,count: resultPage.totalCount
						,jump: function (obj,first) {
							if(first == true){
								return;
							}
							$(".projectList").html("");
							nextPage(obj.curr,10);

						}
					});
					element.render(".projectList");
				}

			});
	}

	$(".search").click(function () {
		console.log("haha");
		search();
		return false;
	});

	function nextPage(pageNum,pageSize) {
		var searchProjectName = $(".searchProjectName").val();
		AJAX.post(cgiMain.applicantAllProject,
			{pageNum:pageNum,pageSize:pageSize,searchProjectName:searchProjectName},
			function (res) {
				if(res.code == '0000'){
					$(".projectList").data("projectList",res.result.list);
					var tpl = $("#projectItemTpl").html();
					var resultPage = res.result;
					for(var i = 0; i < resultPage.list.length;i++){
						var item = resultPage.list[i];
						item.projectCategoryName = categoryMap[item.projectCategory];
						laytpl(tpl).render(item,function (html) {
							$(".projectList").append(html);

							$(".projectList").on("click",'.lookApplyInfo',function (elem) {
								lookApplyInfo(elem);
							});
                            $(".projectList").on("click",'.assignTask',function (elem) {
                                assignTask(elem);
                            });



                        });
					}

					element.render(".projectList");
				}

			});
	}



});

function setAcademist(){
    let params = {};
    AJAX.post(cgiMain.academistAcademistList,
        params,
        function (res) {

            if(res.code == '0000'){
                $(".academistId").data("academistList",res.result.list);
                for(var i = 0; i < res.result.list.length;i++){
                    var item = res.result.list[i];
                    if(!item || !item.id || !item.name){
                        continue;
                    }
                    // if(!firstAcad){
                    //     firstAcad = item;
                    // }
                    $(".academistId").append("<option value='" + item.id +"'>"+ item.name +"</option>");
                }
                // getSubject(firstAcad.id);
                form.render("select");

            }else{
                if(res && res.msg){
                    layer.msg(res.msg);
                }
            }

        });
}

$(".modal-footer > .layui-btn-primary").on("click",function () {

	closeModal();
});

$(".close").on("click",function () {
	closeModal();
});
function closeModal() {
	$("#myModal").hide();
	$("#myModal input, #myModal textarea").val("");
	$("#myModal img").prop("src","");
	$("#myModal embed").remove();
	$(".bpFileDiv").html("")
	$("#previewBp").removeClass();
}

function previewPdf(dom) {
	console.log();
	PDFObject.embed($(dom.target).attr("data-src"),"#previewBp");
}

function assignTask(dom) {
    if(!dom.isPropagationStopped()) {
        var projectId = $(dom.target).attr("data-id");
        $(".assignTaskProjectId").val(projectId);

        var projectList = $(".projectList").data("projectList");
        var project = null;
        for (let i = 0; i < projectList.length; i++) {
            if (projectId == projectList[i].id) {
                project = projectList[i];
                break;
            }
        }

        if (project && project.scoringTasks) {
            let academistList = $(".academistId").data("academistList");
            //添加已有人员
            for (let i = 0; i < project.scoringTasks.length; i++) {
                let item = project.scoringTasks[i];
                let academist;
                for (let j = 0; j < academistList.length; j++) {
                    let itemAcad = academistList[j];
                    if (itemAcad.id == item.academistId) {
                        academist = itemAcad;
                        break;
                    }

                }
                if (!academist) {
                    continue;
                }
                $(".hadTaskAcademists").append("<div><lable>" + academist.name + "</lable>--<label>87分</label><a class='deleteAssignTask' data-id='" +item.id+ "'>    删除</a></div>");
                $(".hadTaskAcademists").on("click", '.deleteAssignTask', function (elem) {
                    // $(elem.target).parent().remove();
                    deleteAssignTask(elem);

                });
            }

        }

        $("#taskModal").show();
    }
    dom.stopPropagation();
}

function deleteAssignTask(dom){
    $(dom.target).parent().remove();
    if(!dom.isPropagationStopped()) {
        var projectId = $(dom.target).attr("data-id");
        let params = {};
        params.id = projectId;
        AJAX.post(cgiMain.deleteAssignScoringTask,
            params,
            function (res) {

                if(res.code == '0000'){
                    layer.msg(res.msg);
                }else{
                    if(res && res.msg){
                        layer.msg(res.msg);
                    }
                }

            });
    }
    dom.stopPropagation();
}


